#C++ enum class
Explore tagged Tumblr posts
removeload-academy · 4 months ago
Text
Understanding C++ Enum Class and Enums: A Complete Guide | Removeload
Enums in C++ provide a convenient way to define a set of named integer constants, improving code readability and reducing errors. The enum keyword has been a part of C++ for a long time, but with the introduction of C++ enum class, developers now have a more type-safe and flexible way to use enumerations. At Removeload Educational Academy, we strive to make programming accessible by offering a free online e-learning tutorial portal that provides live examples to help students learn C++ in an easy and interactive manner. Understanding C++ enum class is essential for writing efficient and maintainable code.
What is C++ Enum Class?
In traditional C++ enums, enumerators are implicitly converted to integers, which can lead to naming conflicts and unintended behavior. To address this, C++ introduced enum class, which provides better type safety by restricting implicit conversions and improving scope resolution.
Here is a simple example of an enum class in C++:#include <iostream> using namespace std; enum class Color { Red, Green, Blue }; int main() { Color myColor = Color::Green; if (myColor == Color::Green) { cout << "The color is Green." << endl; } return 0; }
In this example, Color::Green is explicitly scoped, preventing conflicts with other enumerations or variables named Green. Unlike traditional enums, C++ enum class does not implicitly convert enum values to integers, making the code more robust.
Benefits of Using C++ Enum Class
The key advantages of using enum class over traditional enums include:
Type Safety: Prevents implicit conversions to integers.
Scoped Enumeration: Avoids name conflicts by requiring a prefix (EnumName::Value).
Improved Readability: Makes it clear that values belong to a specific enumeration.
Explicit Underlying Type: Developers can define the underlying data type (e.g., enum class Status : char {}).
For example:enum class Status : int { Success = 1, Failure = 0, Pending = -1 };
This ensures that Status values are strictly integers, enhancing control over memory usage and performance.
Understanding C++ Enums Removeload
Traditional enum types in C++ still have their use cases, especially in legacy systems or scenarios where implicit conversions are beneficial. C++ enums removeload provides flexibility in defining a collection of constants while allowing them to be used interchangeably with integers.
Example of a traditional enum:#include <iostream> using namespace std; enum Days { Monday, Tuesday, Wednesday, Thursday, Friday }; int main() { Days today = Wednesday; cout << "Today is day number: " << today << endl; return 0; }
In this example, Wednesday is automatically assigned the integer value 2, demonstrating how traditional enums implicitly convert to integers.
Choosing Between Enum and Enum Class in C++
While both enum and enum class serve a similar purpose, enum class is recommended for new projects due to its type safety and better scoping. However, C++ enums removeload remains useful for backward compatibility and scenarios requiring implicit integer conversions.
Why Learn C++ with Removeload?
At Removeload Educational Academy, we provide free online tutorials to help students learn programming languages through live examples. Whether you're exploring C++ enum class or understanding C++ enums removeload, our structured tutorials simplify complex topics, making programming more accessible.
Mastering enums in C++ enhances your ability to write cleaner and more efficient code. Keep exploring our tutorials to improve your coding skills and build more robust C++ applications.
0 notes
crystal-wingeddragon-spikes · 3 months ago
Text
Tumblr media Tumblr media
I tried to make something since Animation vs Coding came out. (I don't care about misspelling.)
This is a joke with no punch line because, while it is certainly in-character to these 2 terrorists, it is not a joke I am committed to make. I hope you don't even know what codes they are reacting to.
So, now the punchline is... Everything is so bad from the ground-up, The Dark Lord doesn't know where to start? And The Chosen One somehow ended up insulting ONE normal thing, enraging TDL? Good enough.
I thought about deleting the entire thing, but it was such a perfect way to showcase that me, the author, can "play" a character who much more knowledgeable than I am, because I don't code.
(I don't code beyond getting a bad grade in basic Java and superficially studied C, C++ and C# just to make my resume more attractive. I got my job, I don't care.)
I didn't even know what is an "Enum" before making this comic. Do your research and cherry-pick correct information, and you can fool the average audiences before an actual expert shows up.
One quirk I gave to TCO and TDL (most likely the rest of digital creatures), is that they influenced by the code they speak out loud. TCO has randomized capital letter throughout their speech, but say "Floor" the exact way it appears in code, twice, because string data is case-sensitive. They have free will and can choose not to execute friend certain scripts or simply refuses to say it out loud.
After this, TDL is putting TCO in CODE dot ORG jail. A very great place to start learning, by the way. (Unlike Brilliant, it's free.)
I am explaining things under the cut
You watched AvC, so you already know what is constant and variable... but still;
Gravitational acceleration is a constant.
Speed is a variable.
In your program, you would want some value to change, some to stay the same.
Enum is a type of class.
Class is a collection of data that can either be variables or constant, they can be different data type. Class is good for creating character profile, such as containing both Name (String) and age (Integer).
Enum, is a type of class that only contain constant. If class is a character profile, then, Enum is a lore book that contain things that need to be reference, unchanged, throughout the program. In this comic, Enum is used for items. Unless an upgrade system is involved, items should have the same property.
Me, personally, would simply put name strings in Enum, but actual coding is flexible to make it less of a nightmare to come back and fix, so, as The Dark Lord says, not ideal, but fine.
Not code, PU = Processing Unit, used interchangeably with brain. TDK specifically says that because it sounds like, "Poo".
45 notes · View notes
souhaillaghchimdev · 2 months ago
Text
Game AI Programming
Tumblr media
Artificial Intelligence (AI) in gaming plays a crucial role in creating engaging, dynamic, and realistic experiences for players. From non-player character (NPC) behavior to procedural content generation, game AI programming encompasses various techniques and approaches to make games more immersive. In this post, we will explore the fundamentals of game AI programming and the techniques that developers can use to enhance gameplay.
What is Game AI?
Game AI refers to the techniques and algorithms used to create the illusion of intelligence in non-player characters and other game systems. It allows these entities to react to player actions, adapt to changing environments, and provide challenges, making the game experience richer and more enjoyable.
Key Concepts in Game AI
Pathfinding: Algorithms that determine the shortest route from one point to another (e.g., A* algorithm).
Finite State Machines (FSM): A model that represents the behavior of an NPC through defined states and transitions.
Behavior Trees: A hierarchical model that helps design complex behavior by combining simple actions.
Decision Trees: A flowchart-like structure used for making decisions based on specific conditions.
Fuzzy Logic: A reasoning approach that deals with the uncertainty of inputs to make decisions.
Popular Algorithms in Game AI
A* Pathfinding: Efficiently finds the shortest path on a grid or map.
Minimax Algorithm: Used in two-player games to minimize the possible loss for a worst-case scenario.
Monte Carlo Tree Search (MCTS): A heuristic search algorithm for making decisions in games like Go or Chess.
Genetic Algorithms: A method inspired by natural selection to optimize solutions over generations.
Implementing Basic AI in Unity with C#
Here’s a simple example of a finite state machine to control an NPC's behavior in Unity:using UnityEngine; public class NPC : MonoBehaviour { enum State { Idle, Patrol, Chase } State currentState = State.Idle; void Update() { switch (currentState) { case State.Idle: // Idle behavior if (PlayerInSight()) { currentState = State.Chase; } else { currentState = State.Patrol; } break; case State.Patrol: // Patrol behavior Patrol(); break; case State.Chase: // Chase behavior ChasePlayer(); break; } } void Patrol() { // Patrol logic here } void ChasePlayer() { // Chase player logic here } bool PlayerInSight() { // Logic to check if player is within sight return false; } }
Tools and Frameworks for Game AI Development
Unity: Offers built-in AI tools, NavMesh for pathfinding, and support for behavior trees.
Unreal Engine: Features a robust AI system, including behavior trees and blackboards.
Godot: Lightweight engine with scripting support for AI development.
AI Libraries: TensorFlow and PyTorch for integrating machine learning with games.
Challenges in Game AI Development
Balancing AI difficulty for player engagement
Creating believable and varied NPC behaviors
Optimizing performance to maintain game fluidity
Ensuring AI reacts appropriately to player actions
Best Practices for Game AI Programming
Use modular design to separate AI logic from game logic.
Test AI in different scenarios to ensure robustness.
Incorporate randomness for variability in behavior.
Optimize pathfinding and decision-making algorithms for performance.
Gather player feedback to adjust AI difficulty and behavior.
Conclusion
Game AI programming is an exciting field that enhances the player experience through intelligent behavior and interactions. By understanding the principles of AI and applying them in your games, you can create engaging and challenging experiences that captivate players. Start small, experiment with different techniques, and enjoy the journey of bringing your game characters to life!
0 notes
harmonyos-next · 3 months ago
Text
How to use HarmonyOS NEXT - @Provide and @Consume?
@Provide and @Consume are used for two-way data synchronization with future generations of components, and for scenarios where state data is transmitted between multiple levels. Different from the above-mentioned transfer between father and son components through named parameter mechanism, @Provide and @Consume get rid of the constraints of parameter transfer mechanism and realize cross-level transfer.
Among them, the variable decorated by @Provide is in the ancestor component, which can be understood as a state variable that is "provided" to future generations. The variable decorated by @Consume is the variable provided by the ancestor component in the descendant component.
@Provide/@Consume is a two-way synchronization across component levels. Before reading the @Provide and @Consume documents, it is recommended that developers have a basic understanding of the basic syntax and custom components of the UI paradigm. It is recommended to read in advance: basic syntax overview, declarative UI description, custom components-creating custom components.
The status variable decorated by @Provide/@Consume has the following characteristics:
The state variable decorated by-@Provide is automatically available to all its descendant components, that is, the variable is "provided" to his descendant components. Thus, the convenience of @Provide is that developers don't need to pass variables between components many times.
Descendants use @Consume to obtain variables provided by @Provide, and establish two-way data synchronization between @Provide and @Consume. Unlike @State/@Link, the former can be passed between multi-level parent-child components.
@Provide and @Consume can be bound by the same variable name or the same variable alias, suggesting the same type, otherwise implicit type conversion will occur, resulting in abnormal application behavior.
@Provide/@Consume must specify the type, and the variable types that allow decoration are as follows:
Object, class, string, number, boolean, enum types, and arrays of these types.
Date type is supported.
API11 and above support Map and Set types.
Support the union types defined by the ArkUI framework, such as Length, ResourceStr and ResourceColor.
The type of @Consume variable of-@Provide variable must be the same.
any is not supported.
API11 and above support the union types of the above supported types, such as string | number, string | undefined or ClassA | null. For an example, see @Provide_and_Consume for an example of supporting union types.
Code example [code] // Bound by the same variable name @Provide a: number = 0; @Consume a: number;
// Bound by the same variable alias @Provide('a') b: number = 0; @Consume('a') c: number; [/code]
Code example ProvideConsumePage [code] import { SonComponent } from './components/SonComponent';
@Entry @Component struct ProvideConsumePage { @State message: string = '@Provide and @Consume'; @Provide('count') stateCount: number = 0
build() { Column({space:10}) { Text(this.message) .fontSize(20) .fontWeight(FontWeight.Bold) Button('增加次数').onClick(()=>{ this.stateCount++ }) Text('stateCount='+this.stateCount) SonComponent() } .height('100%') .width('100%')
} } [/code] SonComponent [code] import { GrandsonComponent } from './GrandsonComponent'
@Component export struct SonComponent { build() { Column({ space: 10 }) { Text('这是子组件') GrandsonComponent() } .width('100%') .padding(10) .backgroundColor(Color.Orange)
} } [/code] GrandsonComponent [code] @Component export struct GrandsonComponent { @Consume('count') grandsonCount: number
build() { Column({space:10}){ Text('孙组件') Button('增加次数').onClick(()=>{ this.grandsonCount++ }) Text('grandsonCount='+this.grandsonCount) } .width('100%') .padding(10) .backgroundColor('#EEEEEE') } } [/code]
0 notes
cocoateam · 7 months ago
Text
ScriptableObjects for Weapons
A recent GameJam gave me a chance to jump into Scriptable Objects for my weapons system. Generally I work with enums to build the framework for reuseable components and shared object parameters, but this worked nicely as well.
Here's a reusable Unity C# script for managing weapon pickup and switching. This script allows your character to pick up different weapons, each with unique attributes like damage, fire rate, and prefab.
Setup Steps:
Create Weapon Scriptable Objects: Define each weapon as a ScriptableObject for easy customization.
Attach Pickup Script to Weapons: Add a trigger collider to each weapon prefab and apply this script.
1. Weapon ScriptableObject (WeaponData.cs)
using UnityEngine;
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapons/Weapon")]
public class WeaponData : ScriptableObject
{
public string weaponName;
public WeaponType weaponType;
public float fireRate;
public GameObject weaponPrefab;
public int damage;
public Sprite icon; // Optional: For UI representation
public enum WeaponType { Axe, Knife, Sword, Bow }
}
2. Weapon Pickup System (WeaponPickup.cs)
using UnityEngine;
public class WeaponPickup : MonoBehaviour
{
public WeaponData weaponData; // Assign the weapon data in the inspector
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player")) // Ensure the player has a "Player" tag
{
PlayerWeaponManager weaponManager = other.GetComponent<PlayerWeaponManager>();
if (weaponManager != null)
{
weaponManager.PickupWeapon(weaponData);
Destroy(gameObject); // Destroy the weapon pickup object after pickup
}
}
}
}
3. Player Weapon Manager (PlayerWeaponManager.cs)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerWeaponManager : MonoBehaviour
{
public Transform weaponHolder; // Assign an empty GameObject where weapons will be held
public GameObject currentWeapon;
public WeaponData currentWeaponData;
public void PickupWeapon(WeaponData newWeaponData)
{
// If the player already has a weapon, destroy it
if (currentWeapon != null)
{
Destroy(currentWeapon);
}
// Instantiate the new weapon prefab and set it as a child of the weapon holder
currentWeapon = Instantiate(newWeaponData.weaponPrefab, weaponHolder.position, weaponHolder.rotation, weaponHolder);
currentWeaponData = newWeaponData;
}
// Example method to simulate attacking
public void Attack()
{
if (currentWeaponData != null)
{
Debug.Log($"Attacking with {currentWeaponData.weaponName}, dealing {currentWeaponData.damage} damage.");
}
}
}
How to Use:
Create Weapon Data:
Right-click in the project window.
Select Create -> Weapons -> Weapon Data.
Configure attributes like name, damage, fire rate, and assign a weapon prefab.
Tumblr media
Tumblr media
Create Weapon Prefabs:
Design a weapon prefab with a trigger (Box, capsule, etc.) and then add a checkbox for "IsTrigger"
Add the WeaponPickup script and assign the WeaponData ScriptableObject.
Tumblr media
Tumblr media
Setup Player:
Ensure the player has a collider with the tag "Player."
Add the PlayerWeaponManager script to the player.
Create an empty GameObject (e.g., WeaponHolder) as a child of the player, and assign it in the weaponHolder field.
Tumblr media
Customizable Features:
You can extend WeaponData with additional attributes like ammo, reload time, or special effects.
Enhance PlayerWeaponManager to switch between multiple weapons or add weapon dropping functionality.
This script allows you to create various weapon pickups with unique characteristics, promoting code reusability and easy weapon customization.
0 notes
vafion-vacational-rentals · 10 months ago
Text
A Deep Dive into Rust: The Fastest-Growing Programming Language
Rust has rapidly emerged as one of the most popular programming languages in the developer community. Known for its performance, safety, and concurrency, Rust has earned the title of the “most loved” language in Stack Overflow’s Developer Survey for several years in a row. In this blog, we’ll explore the reasons behind Rust’s meteoric rise, its key features, benefits, and how it is being used in systems programming and beyond.
Why Rust is Gaining Popularity
1. Memory Safety Without Garbage Collection:
   – One of Rust’s most celebrated features is its ability to ensure memory safety without the need for a garbage collector (GC). In languages like C and C++, manual memory management often leads to issues like dangling pointers, buffer overflows, and memory leaks. Rust, however, uses a unique ownership system that ensures memory safety at compile time, preventing these common bugs.
2. Performance Comparable to C and C++:
   – Rust is a systems programming language designed to provide the performance of C and C++ while offering a more modern and safer syntax. It compiles to native code, which allows it to run as fast as traditionally low-level languages. This makes Rust an excellent choice for performance-critical applications like game engines, operating systems, and embedded systems.
3. Concurrency Without Data Races:
   – Concurrency is a key aspect of modern programming, and Rust excels in this area. It guarantees thread safety by preventing data races at compile time. Rust’s ownership model ensures that only one thread can mutate data at any given time, eliminating a whole class of concurrency bugs that plague other languages.
4. A Thriving Ecosystem and Strong Community Support:
   – Rust’s ecosystem has grown rapidly, with a rich set of libraries (crates) available through the Cargo package manager. The Rust community is also known for being welcoming and supportive, making it easier for new developers to learn and adopt the language.
5. Adoption by Major Companies:
   – Many tech giants have started adopting Rust in their codebases. For example, Mozilla (the creators of Rust), Dropbox, Cloudflare, and Microsoft have used Rust to improve performance and security in their products. This real-world adoption showcases Rust’s viability in production environments.
Key Features of Rust
1. Ownership and Borrowing:
   – Rust’s ownership model is its most distinctive feature. Each value in Rust has a single owner, and when the owner goes out of scope, the value is automatically deallocated. This ensures that memory is safely and efficiently managed without the need for garbage collection.
2. Pattern Matching:
   – Rust’s pattern matching is powerful and flexible, allowing developers to handle complex data structures with ease. It is particularly useful in control flow structures like `match` statements, which can destructure enums and other types.
3. Macros:
   – Rust’s macro system allows developers to write code that writes other code (metaprogramming). This can be used to reduce boilerplate, generate code based on patterns, and create domain-specific languages (DSLs) within Rust.
4. Cargo and Crates.io:
   – Cargo is Rust’s build system and package manager, making it easy to manage dependencies, run tests, and build projects. Crates.io is the central repository for Rust libraries, fostering a rich ecosystem of reusable code.
5. Error Handling:
   – Rust takes a pragmatic approach to error handling, encouraging the use of `Result` and `Option` types rather than exceptions. This makes it easier to write robust code that gracefully handles potential failures.
Benefits of Using Rust
1. Safety:
   – Rust’s strict compile-time checks ensure that code is memory-safe and free from common bugs like null pointer dereferencing, buffer overflows, and data races. This leads to more reliable and secure software.
2. Performance:
   – Without the overhead of garbage collection and with fine-grained control over memory usage, Rust can achieve performance on par with C and C++. This makes it suitable for performance-critical applications.
3. Productivity:
   – Despite its focus on safety and performance, Rust is designed to be ergonomic and developer-friendly. Features like pattern matching, powerful enums, and expressive error handling make it easier to write clear and concise code.
4. Concurrency:
   – Rust’s approach to concurrency ensures that code is free from data races, making it easier to write safe concurrent code. This is increasingly important in a world where multi-core processors are the norm.
5. Modern Tooling:
   – Rust’s tooling, particularly Cargo, simplifies the development process by handling dependency management, testing, and building. This allows developers to focus more on writing code and less on managing their development environment.
Use Cases of Rust in Systems Programming and Beyond
1. Operating Systems:
   – Rust’s performance and safety make it an excellent choice for developing operating systems. For example, Redox OS is a modern operating system written entirely in Rust. Its design leverages Rust’s features to create a secure and reliable OS from the ground up.
2. Web Assembly:
   – Rust has strong support for WebAssembly (Wasm), allowing developers to write high-performance code that runs in the browser. This opens up possibilities for web applications that require intensive computations, such as games or image processing tools.
3. Embedded Systems:
   – Rust’s low-level control over hardware makes it ideal for embedded systems development. It allows developers to write safe, concurrent code that runs on resource-constrained devices, such as microcontrollers or IoT devices.
4. Command-Line Tools:
   – Rust is popular for building command-line tools due to its speed, safety, and ease of cross-compilation. Tools like ripgrep (a fast search tool) and exa (a modern replacement for `ls`) showcase Rust’s capabilities in this domain.
5. Networking:
   – Rust’s safety and performance characteristics are particularly beneficial in networking, where reliability and speed are crucial. Projects like Tokio (an asynchronous runtime for Rust) and Actix (a powerful actor framework) have made Rust a popular choice for developing network services and applications.
6. Game Development:
   – Rust is also gaining traction in game development, with game engines like Amethyst and Bevy being developed in Rust. The language’s focus on performance and safety is particularly appealing for game developers who need to manage complex state and real-time computations.
Conclusion
Rust’s rapid rise in popularity is a testament to its unique combination of safety, performance, and modern programming features. Whether you’re building an operating system, a web application, or a command-line tool, Rust offers a powerful set of tools that can help you write efficient and reliable software. As more developers and companies adopt Rust, its ecosystem will continue to grow, making it an even more compelling choice for a wide range of applications. If you haven’t tried Rust yet, now might be the perfect time to dive in and experience what this fast-growing language has to offer. Visit :- https://www.vafion.com/blog/deep-dive-rust-fastest-growing-programming-language/
For more details contact [email protected]
Follow us on Social media  : Twitter |  Facebook | Instagram | Linkedin
0 notes
hackernewsrobot · 11 months ago
Text
Enum class improvements for C++17, C++20 and C++23
https://www.cppstories.com/2024/enum-improvements/
0 notes
myprogrammingsolver · 1 year ago
Text
In this assignment, lets create some kind of hotel management component.
Create modern C++ enumeration (enum class) called RoomType with two items in it, Standard and Comfort. You can find a description of such modern C++ enumerations using the following link (and in million other places too): https://www.codesdope.com/cpp-enum-class/ Keep in mind, enum instances are small. It is ok to pass enum instance by copy. Create modern C++ enumeration (enum class) called…
Tumblr media
View On WordPress
0 notes
sourabhchandrakarbooks3 · 2 years ago
Text
Top 10 Python Coding Secrets in 2023: A Journey through Sourabh Chandrakar Books
Python, a versatile and powerful programming language, continues to evolve, offering developers new tools and techniques to enhance their coding experience. In this article, we will explore the top 10 secret Python coding tips in 2023, drawing inspiration from the invaluable insights found in Sourabh Chandrakar books.
1.Mastering List Comprehensions:
In Sourabh Chandrakar books, you'll find a treasure trove of knowledge on list comprehensions. These concise and readable expressions allow you to create lists in a single line, boosting both efficiency and code elegance. Dive deep into his works to uncover advanced techniques for harnessing the full potential of list comprehensions.
2.Context Managers for Resource Management:
Proper resource management is crucial in Python development.Sourabh Chandrakar emphasizes the use of context managers, and his books delve into the intricacies of the with statement. Learn how to streamline your code and ensure efficient handling of resources like files and database connections.
3.Decorators Demystified:
SourabhChandrakarbooks provide an in-depth exploration of decorators, a powerful Python feature for modifying or extending functions and methods. Unlock the secrets of creating your own decorators to enhance code modularity and reusability.
4.Understanding Generators and Iterators:
Generators and iterators play a pivotal role in optimizing memory usage and enhancing performance. Sourabh Chandrakar insights into these concepts will equip you with the knowledge to write efficient, memory-friendly code.
5.Exploiting the Power of Regular Expressions:
Regular expressions are a potent tool for string manipulation and pattern matching. Sourabh Chandrakar books offer practical examples and tips for mastering regex in Python, enabling you to write robust and flexible code for text processing.
6.Optimizing Code with Cython:
Take your Python code to the next level by exploring the world of Cython. Chandrakar expertise in this area is evident in his books, guiding you through the process of integrating C-like performance into your Python applications.
7.Advanced Error Handling Techniques:
Sourabh Chandrakar places a strong emphasis on writing robust and error-tolerant code. Delve into his books to discover advanced error handling techniques, including custom exception classes and context-specific error messages.
8.Harnessing the Power of Enums:
Enums provide a clean and readable way to represent symbolic names for values. Sourabh Chandrakar's books shed light on leveraging Enums in Python to enhance code clarity and maintainability.
9.Mastering the asyncio Module:
Asynchronous programming is becoming increasingly important in modern Python development. Explore Chandrakar insights into the asyncio module, uncovering tips for efficient asynchronous code design.
10.The Art of Unit Testing:
Comprehensive unit testing is a hallmark of professional Python development. Sourabh Chandrakar books guide you through the art of writing effective unit tests, ensuring the reliability and maintainability of your codebase.
Conclusion:
In the dynamic world of Python development, staying ahead requires constant learning and exploration. Sourabh Chandrakar books serve as a valuable resource, offering deep insights into advanced Python coding techniques. By incorporating these top 10 secret Python coding tips into your skill set, you'll be well-equipped to tackle the challenges of 2023 and beyond. Happy coding!
1 note · View note
kumarom · 2 years ago
Text
C# Enum
Enum in C# is also known as enumeration. It is used to store a set of named constants such as season, days, month, size etc. The enum constants are also known as enumerators. Enum in C# can be declared within or outside class and structs.
Tumblr media
0 notes
removeload-academy · 2 months ago
Text
youtube
C++ User-defined Data Types in Hindi | Struct Data Type in C++ | Union Data Type | C++ Tutorials
In C++, user-defined data types are types that are defined by the programmer, allowing them to create custom data structures. These types are defined using the class, struct, union, or enum keywords in C++. These types are essential for creating more complex and flexible programs that go beyond the built-in data types. For more Details, Kindly check my website URL. https://www.removeload.com/cpp-data-types
0 notes
wuggen · 4 months ago
Text
I mean, in OOP you're similarly beholden to the language's decisions on how to implement and lay out classes and class instances, yeah? Like, your entire beef with Java (as far as I can infer from this post) is that it doesn't give you the same low-level control as C++ does, but it does give you the same ability to partition state and create interfaces; those two properties of a language are basically orthogonal. Meanwhile Rust's implementation of ADTs is much closer to C++'s implementation of classes than it is to Haskell's implementation of ADTs (which is in turn much closer to Java's implementation of classes). And unlike Haskell, Rust gives you access to those low-level features for which you praise C++, and the memory characteristics of its ADTs are much more concretely defined and programmer-visible than Haskell's. A Rust struct with methods is laid out and behaves at runtime nearly identically to a C++ class, a Rust trait object nearly identically to an instance of a C++ virtual class, and a Rust enum nearly identically to a C/C++ tagged union
i have yet to encounter a legitimate use case for OOP. many illegitimate ones, of course! but it's just one of those perennial bad ideas that always creates more problems than it solves. put it to rest.
108 notes · View notes
izicodes · 3 years ago
Note
Hiya! Just found your blog, and first of all it’s awesome that you’re learning so many things!! and there’s so much progress good job :000
My best friend started a course on c# coding but they’ve been feeling so stressed out that they have been avoiding it for the longest time, that i decided that i’ll learn as well and help them cause i want them to succeed, understand and be confident!!
But uhhhh… obviously i don’t have access to the course that they are doing, and they don’t have notes for me, cause they haven’t been doing it….
Can you please point me to good starting out c# resources? And uhh probably a question for the future, would it be okay if i would pop in here from time to time with questions about code? thank you in advance for answering and please have a wonderful day, don’t forget to take breaks and drink water!
Tumblr media
Hallo Hallo! ≧◉◡◉≦
I’m sorry your friend is struggling with C# right now, C# is literally the hardest programming language I’ve tried yet so I understand the feeling. I just submitted a C# project that was due on the 18th of April… I just couldn’t understand Abstract classes and Interface and it took me a month to understand them. Sometimes I just need a break from C# altogether! But props to you for wanting to learn C# and help them, especially since you’re going the self-taught route!
So, C# resources! As I am still learning (only 6 months into my apprenticeship) my advice is like amateur/junior level! But I’ll try my best! This is my advice and I know some more experienced c# programmers might be like “Erm, no?” but hey ho I’m trying my best!
Microsoft C# Documentation
Use this like your religious/spiritual book. It’s hella confusing at first but always just refer back to this, especially good practises and error codes you don’t understand. I recommend going over the ‘Learn to program in C#’, ‘C# fundamentals’ and ‘Key Concepts’. Just skim read them, watch the videos, do the tutorials, save them on your computer to look back, make notes and more. Read read read until you understand. And if you can’t, there’s Youtube that can visually show you how.
The way my teacher taught C#
This is the order he taught us and I am very confident up to Topic 9. I’m still going over notes from there on and doing the homework. If you have any questions from topics 1 to 8, I’d be happy to help! WinForms and Databases (C# x SQL) were included because I did those before my C# learning but I can help with those too!
The basics - installing Visual Studio, first console app, first WinForm
Methods
Intro to Conditionals
More on Conditionals
Loops
Arrays
Object-Oriented Programming - data types, classes, objects, the fours OOP concepts with C#
OOP - fields and methods
Enums and Strings
Collections and Generics
Working with files
The meaning of ‘static’
Exceptions
Intro to Inheritance
Inheritance towards Polymorphism
Abstract classes and Interfaces (where I had struggles with recently ahaha)
Generic Interfaces
Introduction to Testing
Solid principles and Design patterns
C# Learning Websites
C# Tutorial by Demo2s
C# Tutorials by BrainBell
C# programming by TutorialsTeacher
Learn c# Programming by Programiz
C# Tutorial for Beginners by Guru99
C# Tutorial by C#Station
C# by Learncs.org
C# / CSharp Tutorial by Java2s
Youtube Channels
FreeCodeCamp.org C# Section
Programming with Professor Sluiter
Academy Artan
ProgrammingGeek
ASPNET WEBFORM
Barry Solomon
Fox Learn
The C# Academy
Shaun Halverson
RJ Code Advance EN
Obviously, there are loads more but these are the ones I like the most. Some of them are like years old but still relevant in terms of the basic concepts of each topic. And some are more project-oriented.
Youtube Playlists
Beginning C# by Programming with Professor Sluiter
Programming in C# by mkaatr
C#.NET Tutorials by Programming with Mosh
C# Complete Tutorial From Beginner To Advance by FL Developers - 8 hours but please take your time, make notes and follow him, he's really good imo
C# Tutorials by Caleb Curry
C# Excerises/Homework/Projects
C# Sharp Programming Exercises, Practice, Solution by w3resource
Practise Exercises C# Sharp
C# by Exercism
250+ C# Basic: Exercises, Practice, Solution | C# programming examples and solutions by Tech Study
 Visual C# exercises by WiseOwl
Online Books
C Sharp Programming Book (226 pages)
Introduction to C#  (65 pages)
Other books on C#Corner
Discord
I would recommend joining a community for help and inspiration. I joined one on Discord called C# (LINK), they have like actual C# experts on there - Had one read my code and he said it looked great, I literally melted in my seat I was so happy XD
I hope this helps as a starter! And like you mentioned, you can dm or ask me any questions. And if you’re in need of homework for topics, I can give you similar homework tasks my tutor gave us / make some up for you, I don’t mind. BUT REMEMBER I am still like beginner/Junior (I would say more low-level Junior) with C# so if I’m like uhhhh, I’ll just ask my tutor/my colleagues at work and see if they can give feedback.
But yeah! This is all I can think of right now as help! Dm me if you are stuck on anything! Have a nice day! ᕙ(`▿´)ᕗ
116 notes · View notes
adamtheamazing5 · 3 years ago
Video
tumblr
C# Advanced basics post-mortem
This time I decided if I want to make bigger projects, I needed to understand more specifically about the C# programming language I use and how it works so I can understand it to make the best fun games as possible.
I even made 3 short mini games as a little exercises to warm myself up.
What I learned
 different types of variables like doubles, characters, and colour.
different ways of how variables/ parameters add with each other, e.g.  float sum = (2 + 3) * (4 - (4 / 3)).
A better understanding of Enums and how the states can be used. e.g played dies or at main menu waiting for player to press play or restart, what happens next?  does he move a inch or not?
The calculated difference of float and int when dividing them respectfully such as calculating the nearest inside numbers (part of floats).
 Casting: Converts a variable to another variable. Eg int a = 5 into float a = 5.0f.
How more robust Lists can be, such as being counted, added, removed specifically or all selected, reversed, removed at range and etc. Also, an idea of what its generics are <>.
Different types of functions that can be used like voids, ints, floats and returning their parameters such as strings, ints and floats.
Functions store many parameters as much as they need. Also different types of functions can share the same name, except for the same types.
How effective and distinctive behaviour of If, if else and else statements of controlling mechanics.
Not to have so many if statements in a nested code otherwise it may affect performance of the game.
More detailed info, cleaner code, similarities to the ifs, if else, else statements and how complex switch Statements of how they execute with different variables to run code inside each of the cases and defaults.
the unique behaviour of breaks that break out of the code to execute outside code.
The Different types of loops such as For loops, for each loops, do while loops of how their used respectfully so it doesn't crash the computer on the wrong use.
Better understanding of Arrays of what the elements can contain such as ints, game objects, floats, bools, strings, doubles etc and how it can only be programmed to access their elements not outside its index or length.
How you can change array element values by code without setting its variables.
How for loop doesn't need to be specialised how many times to repeat the loop so it doesn't crash.
Advanced use of Coroutines such as Stopping Coroutines, waiting for seconds in real time (no matter how slow or fast the game is with time scale), how they can pass Parameters and strings to reference other functions and how the waitforseconds can be slowed or speed up by Time.TimeScale.
Passing arrays into void  returning functions like ints. The parameters can even have the same names of its variables and it won't cause an error.
How interesting is to model objects from classes each with their variables and to update them overtime.
How useful are constructors when passing variables.
How "this." refers to the class variable and outside the function parameters.
Difference of Objects create that get passed in Memory as references and values.
 More detail of Data encapsulation/visibility modifiers other than public or private. I learnt more such as Internal, protected modifiers, setting and getting variables.
 A deeper understanding of inheritance such as from Mono behaviour and from other classes such as behaviours, functions, properties and variables.
How Inheritance works with child game classes using override functions to override the virtual function from their parent classes to do something else.
Most functions, datatypes values including transforms which are inherited from Mono behaviour.
The pros and cons of method overloading, while good to use a variety of functions and parameters, but needs to be specific of which function and parameters to run.
The use of the Ternary Operator such as using ? (if) and : (else) respectfully like if statements.
Variable Attributes and such as [RequireComponent], [ExecuteInEditMode], [AddComponentMenu], [HideInInspector], [Range]and [TextArea] which are broadly useful to read and get components to reduce unexpected issues, and makes the life's easier for designers, respectfully.
 How static variables and functions can work together with each other's scripts without get components and creating objects. They also don't work with non-static variables and functions.
How Delegates can be used to subscribe or call events from scripts including statics
How to return value answers when adding or subtracting.
How to make log warnings and log errors execute by code in the console depending how the script is written.
-Pumpkins and Golems
The possibility that I can make a game based on its rigid body physics a little more than complex code. E.g dodging rolling pumpkins from a slope, etc
-Bombs Away
Being able to spawn bombs in-between min and max distances with floats randomly from one transform variable.
Being able to restrict players movement with floats, Vector 2 and if statements without using a box collider.
-Knife Hit
Able to add force on knife with either Space or Mouse keys respectfully without causing unwanted design issues or bugs.
Able to set the knife game object to be parent of the wood by collisions and turning off collisions with "Detect Collisions" by turning it false on the knife once collided.
Overall
It was a long and hard work to get a better understanding with these datatype concepts. But I'm glad that I've done it so I can get a better understanding of how C# works so that way once I start to make more complex games, I am more aware of how it works so its easier to understand, fix unexpected bugs, and work differant ways to execute code.
10 notes · View notes
shieldfoss · 4 years ago
Text
So You Like Pure Functions But Don’t Like Exceptions So You Need A Different Way To Do Errors?
lov too template
#include <variant> template<typename A, typename B> class twin { public: template<typename C> twin(C c) : var_(c){}; template<typename C> bool is() const noexcept { return std::holds_alternative<C>(var_); } template<typename C> [[nodiscard]] C const & as() const { return std::get<C>(var_); } private: std::variant<A,B> var_; }; enum class error { firstError, secondError }; twin<int,error>getIntOrError() { //return error::firstError; //return error::secondError; return 3; } int main() { auto const result = getIntOrError(); if(result.is<error>() && result.as<error>()==error::firstError) { return 1; } if(result.is<error>() && result.as<error>()==error::secondError) { return 2; } if(result.is<int>()) { return result.as<int>(); } }
20 notes · View notes
janokenmun · 3 months ago
Text
oki!
so my favorite features are like:
-tuples; these are great for returning multiple arguments really easily, without fucking around with pointers like C or defining a new class for Every Multiple-Returns Function like java. u just do something like:
return (5, 0.2, false);
and it Just Works. to read the returned values, you can do this:
(someInt, someDouble, someBool) = someFunction();
-enums; rust enums/unions are really really nice. they're how i generally handle polymorphism-like structures (although you can do this with traits (interfaces) as well which feels more standard OOP); each option for the enum can have its own set of data different from the others, and you don't need to keep track of which one it is manually (unlike C unions). an example from the rust book is:
enum IpAddr { V4(u8, u8, u8, u8), V6(String), }
where this enum has 2 options; either ipv4 (4 numeric bytes), or ipv6 (a String)
null pointers actually don't exist in rust, that's usually handled with the Option enum (options either Some(T) or None, where T is generic type); this is also used for a lot of things where returning it could fail (along with the Result enum which is basically the same except its err instead of none and it has an error u can read)
as for downsides; i mentioned that it doesn't have proper inheritance. its main OOP stuff comes from Traits; i haven't used these much (i'm not much of an OOP guy), but from what i understand these are basically just interfaces like in java, and they can inherit from eachother (requiring that any class that implements the child interface implement all the stuff of the parent interface). classes cannot inherit from eachother though, it's only traits. these DO let you do polymorphism though
aside from that its language design has a lot of making it hard to mess things up. null pointer exceptions don't exist. there's strong compile-time checks for a lotta things. even multithreading is designed to be as secure and compile-time-checkable as possible. its like the opposite of C/C++ in that regard
If any Haskell and or Rust fans follow me, give me 1 good reason to learn them
33 notes · View notes